package com.joe.updemo.http;

import android.content.Context;
import com.google.gson.JsonObject;
import com.joe.updemo.R;
import com.joe.updemo.http.dataStructure.BasicResponse;
import com.joe.updemo.http.dataStructure.JsonParams;
import com.joe.updemo.http.listener.TransApiResultListener;
import com.joe.updemo.http.loader.ApiLoader;
import com.joe.updemo.http.retrofit.RetrofitObserver;
import com.joe.updemo.utils.ApiConstant;
import com.joe.updemo.utils.LogUtil;
import com.joe.updemo.utils.PayMD5Util;
import com.joe.updemo.utils.manager.ToastUtil;

import static com.joe.updemo.utils.PayContext.DEMO_KEY;


public class ApiHelper {
    private Context mContext;
    private ApiLoader mApiLoader;

    private static class Holder {
        private static final ApiHelper mHelper = new ApiHelper();
    }

    public Context getContext() {
        return mContext;
    }

    private void setContext(Context context) {
        if (context != null) {
            mContext = context;
        }
        mApiLoader = new ApiLoader();
    }

    public static ApiHelper getInstance(Context context) {
        Holder.mHelper.setContext(context);
        return Holder.mHelper;
    }

    public void OrderAPI(final String money, final TransApiResultListener<String> listener) {
        JsonParams params = new JsonParams();
        params.put("OrderId", String.valueOf(System.currentTimeMillis()));
        params.put("TradeMoney", money);
        String sign = PayMD5Util.getMD5(params.getJsonObject() + DEMO_KEY);
        mApiLoader.postHttpObserve(ApiConstant.ORDER_API, params)
                .subscribe(new RetrofitObserver<BasicResponse<JsonObject>>(mContext) {
                    @Override
                    public void onSuccess(BasicResponse<JsonObject> response) {
                        super.onSuccess(response);
                        LogUtil.log("OrderAPI： " + response.toString());
                        try {
                            listener.trans(response.getData().get("Url").getAsString());
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.showShort(R.string.response_return_error);
                        }
                    }
                });
    }

}
